package com.tomjun.permission.controller;

import java.util.Map;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
/**
 * 用户的操作，比如用户的新增修改删除以及角色的绑定
 * @author admin
 *
 */
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.tomjun.common.JsonModel;
import com.tomjun.permission.model.UserInfo;
import com.tomjun.permission.service.UserService;

@RestController
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;
	/**
	 * 分页获取所用的用户信息
	 * @param page
	 * @param pageSize
	 * @param map
	 * @return
	 */
	@RequiresPermissions("user:list")
	@RequestMapping(value = "/{page}/{pageSize}",method = RequestMethod.GET)
	public JsonModel<Object> getAllUser(@PathVariable("page") int page,@PathVariable("pageSize")int pageSize,
			@RequestParam Map<String, Object> map){
		JsonModel<Object>  jsonModel=new JsonModel<Object>();
		try {
			return userService.getAllUser(page, pageSize, map);
		} catch (Exception e) {
			// TODO: handle exception
			jsonModel.setCode(1);
			jsonModel.setMsg("fail");
		}
		return jsonModel;
	}
	
	/**
	 * 更新用户数据
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:update")
	@RequestMapping(value = "/updateUser",method = RequestMethod.PUT)
	public JsonModel<String> updateUserInfo(@RequestBody UserInfo user){
		try {
			userService.updateUserInfo(user);
			return new JsonModel<String>().generateSuccess(null);
		} catch (Exception e) {
			// TODO: handle exception
			return new JsonModel<String>().generateFailue("fail");
		}
	}
	/**
	 * 新增用户数据
	 * @param user
	 * @return
	 */
	@RequiresPermissions("user:add")
	@RequestMapping(value = "/add",method = RequestMethod.POST)
	public JsonModel<String> addUser(@RequestBody UserInfo user){
		JsonModel<String> userModel=new JsonModel<String>();
		try {
			//判断用户是否存在
			int count=userService.existUser(user.getUsername());
			if(count>0) {
				userModel.setCode(1);
				userModel.setMsg("用户已经存在");
				return userModel;
			}
			userService.addUser(user);
			return userModel.generateSuccess(null);
		} catch (Exception e) {
			// TODO: handle exception
			return userModel.generateFailue("fail");
		}
	}
	
	/**
	 * 删除用户数据,这里是软删除
	 * @return
	 */
	@RequiresPermissions("user:update")
	@RequestMapping(value = "/{id}",method = RequestMethod.DELETE)
	public JsonModel<String> deleteUser(@PathVariable("id") int id){
		try {
			userService.deleteUser(id);
			return new JsonModel<String>().generateSuccess(null);
		} catch (Exception e) {
			// TODO: handle exception
			return new JsonModel<String>().generateFailue("fail");
		}
	}
}
